package com.meiyu.live.tv.widget;

import android.animation.Animator;
import android.animation.PropertyValuesHolder;
import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.AnimationDrawable;
import android.os.Handler;
import android.util.AttributeSet;
import android.view.View;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import com.meiyu.live.popj.Gift;
import com.meiyu.live.util.AnimationUtil;

import java.io.File;
import java.io.IOException;
import java.util.LinkedList;
import java.util.Queue;

import pl.droidsonroids.gif.GifDrawable;
import pl.droidsonroids.gif.GifImageView;

/**
 * Created by zbl on 2016/12/23.
 */
public class GiftGifShowView extends GifImageView {

    private static final long TASK_GAP = 800;

    private Context context;
    private ImageLoader imageLoader;
    private DisplayImageOptions options;
    private Handler handler = new Handler();

    private Queue<Gift> queue = new LinkedList<>();

    private GifDrawable gifDrawable;
    private boolean isRunning = false;

    public GiftGifShowView(Context context) {
        super(context);
        init(context);
    }

    public GiftGifShowView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    private void init(Context context) {
        this.context = context;
        imageLoader = ImageLoader.getInstance();
        options = new DisplayImageOptions.Builder()
                .cacheInMemory(false)                        // 设置下载的图片是否缓存在内存中
                .cacheOnDisk(true)                          // 设置下载的图片是否缓存在SD卡中
                .build();
        setAlpha(0f);
    }

    private Runnable playAnimInvisibleTask = new Runnable() {
        @Override
        public void run() {
            playAnimInvisible();
        }
    };

    private Runnable addGifTask = new Runnable() {
        @Override
        public void run() {
            setImageDrawable(null);
            if (gifDrawable != null && !gifDrawable.isRecycled()) {
                gifDrawable.recycle();
            }
            Gift gift = queue.poll();
            if (gift == null) {
                isRunning = false;
            } else {
                showGif(gift);
            }
        }
    };

    private void showGif(Gift gift) {
        isRunning = true;
        setAlpha(1f);
        int[] animRes = AnimationUtil.getAnimationResByGiftId(gift.gift_type);
        int animResId = animRes[1];
        long animDuration = animRes[2];
        if (animResId != -1) {

            setImageResource(animResId);
            AnimationDrawable animationDrawable = (AnimationDrawable) getDrawable();
            animationDrawable.start();
            long duration = animDuration;
            handler.postDelayed(playAnimInvisibleTask, duration);
        } else {
            imageLoader.loadImage(gift.animation, options, new ImageLoadingListener() {
                @Override
                public void onLoadingStarted(String imageUri, View view) {
                }

                @Override
                public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
                    handler.post(addGifTask);
                }

                @Override
                public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
                    try {
                        File file = imageLoader.getDiskCache().get(imageUri);
                        if (file != null && file.exists()) {
                            gifDrawable = new GifDrawable(file);
                            long duration = gifDrawable.getDuration();
                            setImageDrawable(gifDrawable);
                            handler.postDelayed(playAnimInvisibleTask, duration);
                        } else {
                            handler.post(addGifTask);
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                        handler.post(addGifTask);
                    }
                }

                @Override
                public void onLoadingCancelled(String imageUri, View view) {

                }
            });

        }

    }

    public void addGif(Gift gift) {
        if (isRunning) {
            queue.offer(gift);
        } else {
            showGif(gift);
        }
    }

    private void playAnimInvisible() {
        PropertyValuesHolder propertyValuesHolder = PropertyValuesHolder.ofFloat("alpha", 1.0f, 0.0f);
        ValueAnimator animator = ValueAnimator.ofPropertyValuesHolder(propertyValuesHolder);
        animator.setDuration(TASK_GAP);
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator valueAnimator) {
                float alpha = (float) valueAnimator.getAnimatedValue("alpha");
                setAlpha(alpha);
            }
        });
        animator.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {

            }

            @Override
            public void onAnimationEnd(Animator animation) {
                handler.post(addGifTask);
            }

            @Override
            public void onAnimationCancel(Animator animation) {

            }

            @Override
            public void onAnimationRepeat(Animator animation) {

            }
        });
        animator.start();
    }
}
